package com.martin.lib_base.net.body

import com.martin.lib_base.ktx.loge
import com.martin.lib_base.ktx.toJson
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*

/**
 * @author：孟凡华
 * @date：2022/4/10 20:09
 */
class ProgressResponseBody(
    private val url: String,
    private val body: ResponseBody,
    private val progressCallback: (url: String, total: Long, current: Long, progress: Int) -> Unit
) : ResponseBody() {

    private val bufferedSource: BufferedSource by lazy {
        buildSource(body.source()).buffer()
    }

    override fun contentLength(): Long {
        return body.contentLength()
    }

    override fun contentType(): MediaType? {
        return body.contentType()
    }

    override fun source(): BufferedSource {
        return bufferedSource
    }

    private fun buildSource(source: Source): Source {
        return object : ForwardingSource(source) {
            var totalBytesRead = 0L
            var progress = 0

            override fun read(sink: Buffer, byteCount: Long): Long {
                val read = super.read(sink, byteCount)
                totalBytesRead += if (read != -1L) read else 0L
                val contentLength = contentLength()
                val p = (totalBytesRead * 100 / contentLength).toInt()
                //当前进度大于之前进度,才通知
                if (p > progress) {
                    progress = p
                    progressCallback(url, contentLength, totalBytesRead, p)
                }
                return read
            }
        }
    }

}